import React, {useEffect, useMemo, useRef, useState} from "react";
import { DatePicker } from "antd";
import st from '../editable-text/editable-text.module.css'
import {BehaviorSubject, skip} from "rxjs";
const { RangePicker } = DatePicker

let id = 1

interface PropsType {
    placeholder?: string
    style?: React.CSSProperties
    onDateChange?: (value: [string, string]) => void
    defaultStartDate?: string
    defaultEndDate?: string
}


export const EditableDateText: React.FC<PropsType> = ({
    style= {},
    placeholder= '填写开始 - 结束日期',
    onDateChange = () => {},
    defaultStartDate = '',
    defaultEndDate = ''
    }) => {
    const rangePickerRef = useRef(null)
    const hostRef = useRef(null)
    const [[startDate, endDate], setValue] = useState<[string, string]>([defaultStartDate, defaultEndDate])
    const [displayPicker, setDisplayPicker] = useState(false)
    const [isOpen, setIsOpen] = useState(false)
    const isSelectedDate = startDate && endDate
    const dateText = isSelectedDate ? `${startDate} - ${endDate}` : ''

    const valueChangeEmit = useMemo(() => new BehaviorSubject<[string, string]>(['', '']), [])
    const compId = useMemo(() => 'ed-dt' + id++, [])

    const outSideClick = (e: MouseEvent) => {
        const el = hostRef.current as any as HTMLDivElement
        const drp = document.querySelector(`.ant-picker-dropdown.${compId}`)
        if (!drp) { return; }
        // 点击的元素不在 本组件根元素内 并且不在日期选择框内
        if (!el.contains(e.target as any) && !drp.contains(e.target as any)) {
            setIsOpen(false)
            setDisplayPicker(false)
        }
    }

    useEffect(() => {
        if (!displayPicker) {
            valueChangeEmit.next([startDate, endDate])
        }
    }, [displayPicker])

    useEffect(() => {
        document.addEventListener('click', outSideClick)

        const subscription = valueChangeEmit.pipe(
            skip(1),
        ).subscribe((date) => {
            onDateChange(date)
        })
        return () => {
            document.removeEventListener('click', outSideClick)
            subscription.unsubscribe();
        }
    }, [])


    function onClickText() {
        setDisplayPicker(true)
        setIsOpen(true)
        Promise.resolve().then(() => {
            const picker = rangePickerRef.current as unknown as {
                focus: () => void;
                blur: () => void
            }
            picker.focus();
        })
    }
    return <div ref={hostRef} id={compId} className={st['editable-text']}>
        <RangePicker
            style={{display: displayPicker ? 'inline-flex' : 'none'}}
            open={isOpen}
            size={'small'}
            popupClassName={compId}
            onFocus={(e) => {
                setIsOpen(true)
            }}
            onChange={(d, dateString) =>{
                setValue(dateString)
            }}
            ref={rangePickerRef} picker='month'></RangePicker>
            <span onClick={() => onClickText()} style={{...style, display: displayPicker ? 'none' : 'initial'}}>{dateText}</span>
            {!isSelectedDate ?
            <span className={st['et-placeholder']}
                 style={{display: displayPicker ? 'none' : 'initial'}}
                 onClick={() => onClickText()}>{placeholder}</span>
            : null}
    </div>

}
